<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="####1. 网络状态改变使用静态注册还是动态注册回答： 动态注册。因为当App关闭后，我们的应用将不再关心网络状态的改变了。">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="Android-网络改变状态监听">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/Android-Special-Function/Android-网络改变状态监听/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="####1. 网络状态改变使用静态注册还是动态注册回答： 动态注册。因为当App关闭后，我们的应用将不再关心网络状态的改变了。">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-9a7038b81e3f64c6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-08-06T11:10:23.553Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android-网络改变状态监听">
<meta name="twitter:description" content="####1. 网络状态改变使用静态注册还是动态注册回答： 动态注册。因为当App关闭后，我们的应用将不再关心网络状态的改变了。">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/3110861-9a7038b81e3f64c6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/Android-Special-Function/Android-网络改变状态监听/"/>





  <title>Android-网络改变状态监听 | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/Android-Special-Function/Android-网络改变状态监听/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Android-网络改变状态监听</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:38+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>####1. 网络状态改变使用静态注册还是动态注册<br>回答： 动态注册。因为当App关闭后，我们的应用将不再关心网络状态的改变了。 </p>
<a id="more"></a>
<p>####2. 添加必须的权限<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;</span><br><span class="line">&lt;!--允许读取网络状态--&gt;</span><br><span class="line">&lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot;/&gt;</span><br><span class="line">&lt;!--允许读取wifi网络状态--&gt;</span><br><span class="line">&lt;uses-permission android:name=&quot;android.permission.ACCESS_WIFI_STATE&quot;/&gt;</span><br></pre></td></tr></table></figure></p>
<p>####3. 静态注册<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&lt;!--静态注册--&gt;</span><br><span class="line">&lt;receiver</span><br><span class="line">    android:name=&quot;.NetReceiver&quot;</span><br><span class="line">    android:enabled=&quot;true&quot;</span><br><span class="line">    android:exported=&quot;true&quot;&gt;</span><br><span class="line">    &lt;intent-filter&gt;</span><br><span class="line">        &lt;action android:name=&quot;android.net.conn.CONNECTIVITY_CHANGE&quot;/&gt;</span><br><span class="line">        &lt;action android:name=&quot;android.net.wifi.WIFI_STATE_CHANGED&quot;/&gt;</span><br><span class="line">        &lt;action android:name=&quot;android.net.wifi.STATE_CHANGE&quot;/&gt;</span><br><span class="line">    &lt;/intent-filter&gt;</span><br><span class="line">&lt;/receiver&gt;</span><br></pre></td></tr></table></figure></p>
<p>####4. 动态注册<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">public class MainActivity extends AppCompatActivity &#123;</span><br><span class="line"></span><br><span class="line">    private NetReceiver mReceiver;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onCreate(Bundle savedInstanceState) &#123;</span><br><span class="line">        super.onCreate(savedInstanceState);</span><br><span class="line">        setContentView(R.layout.activity_main);</span><br><span class="line"></span><br><span class="line">        mReceiver = new NetReceiver();</span><br><span class="line">        IntentFilter filter = new IntentFilter();</span><br><span class="line">        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);</span><br><span class="line">        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);</span><br><span class="line">        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);</span><br><span class="line">        registerReceiver(mReceiver, filter);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onDestroy() &#123;</span><br><span class="line">        super.onDestroy();</span><br><span class="line">        unregisterReceiver(mReceiver);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>####5. NetReceiver代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 网络状态监听广播</span><br><span class="line"> * 监听网络的改变状态，只有在用户操作网络连接开关(wifi, mobile)的时候接收广播，</span><br><span class="line"> * 然后再对应的界面进行相应的操作，并将状态保存在我们的app里面</span><br><span class="line"> * @author mazaiting</span><br><span class="line"> */</span><br><span class="line">public class NetReceiver extends BroadcastReceiver &#123;</span><br><span class="line">    private static final String TAG = &quot;NetReceiver&quot;;</span><br><span class="line">    public NetReceiver() &#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void onReceive(Context context, Intent intent) &#123;</span><br><span class="line"></span><br><span class="line">        /**</span><br><span class="line">         * 这个监听wifi的打开与关闭，与wifi的连接无关</span><br><span class="line">         */</span><br><span class="line">        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) &#123;</span><br><span class="line">            // 获取Wifi状态</span><br><span class="line">            int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);</span><br><span class="line">            Log.e(TAG, &quot;onReceive: &quot; + wifiState);</span><br><span class="line"></span><br><span class="line">            switch (wifiState) &#123;</span><br><span class="line">                case WifiManager.WIFI_STATE_ENABLING:</span><br><span class="line">                    // Wifi开启中</span><br><span class="line">                    Log.e(TAG, &quot;onReceive: Wifi开启中&quot;);</span><br><span class="line">                    break;</span><br><span class="line">                case WifiManager.WIFI_STATE_ENABLED:</span><br><span class="line">                    // Wifi可用</span><br><span class="line">                    Log.e(TAG, &quot;onReceive: Wifi可用&quot;);</span><br><span class="line">                    break;</span><br><span class="line">                case WifiManager.WIFI_STATE_DISABLING:</span><br><span class="line">                    // Wifi关闭中</span><br><span class="line">                    Log.e(TAG, &quot;onReceive: Wifi关闭中&quot;);</span><br><span class="line">                    break;</span><br><span class="line">                case WifiManager.WIFI_STATE_DISABLED:</span><br><span class="line">                    // Wifi已关闭</span><br><span class="line">                    Log.e(TAG, &quot;onReceive: Wifi已关闭&quot;);</span><br><span class="line">                    break;</span><br><span class="line">                case WifiManager.WIFI_STATE_UNKNOWN:</span><br><span class="line">                    // Wifi状态未知</span><br><span class="line">                    Log.e(TAG, &quot;onReceive: Wifi未知&quot;);</span><br><span class="line">                    break;</span><br><span class="line">                default:</span><br><span class="line">                    break;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        /**</span><br><span class="line">         * 监听Wifi的连接状态，即是否连上了一个有效无线路由，当上变广播的状态时WifiManager.WIFI_STATE_DISABLING,</span><br><span class="line">         * 和WIFI_STATE_DISABLED的时候，根本不会解到这个广播在上边广播接到是WifiManager.WIFI_STATE_ENABLED状态</span><br><span class="line">         * 的同时也会接到这个广播，当然刚打开wifi肯定还没有连接到有效的无线</span><br><span class="line">         */</span><br><span class="line">        if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) &#123;</span><br><span class="line">            // 获取网络信息</span><br><span class="line">            Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);</span><br><span class="line">            if (null != parcelableExtra) &#123;</span><br><span class="line">                // 强转为NetworkInfo对象</span><br><span class="line">                NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;</span><br><span class="line">                // 获取网络状态</span><br><span class="line">                NetworkInfo.State state = networkInfo.getState();</span><br><span class="line">                // 判断状态</span><br><span class="line">                boolean isConnection = state == NetworkInfo.State.CONNECTED;</span><br><span class="line">                Log.e(TAG, &quot;onReceive: &quot; + isConnection);</span><br><span class="line">                Toast.makeText(context, &quot;当前状态： &quot; + isConnection , Toast.LENGTH_SHORT).show();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        /**</span><br><span class="line">         * 这个监听网络连接的设置，包括Wifi和移动数据的打开和关闭</span><br><span class="line">         * 最好还是用这个监听，Wifi如果打开，关闭以及链接上可用的连接都会接到监听</span><br><span class="line">         * 这个广播的最大的弊端势必上边两个广播的反应都要慢</span><br><span class="line">         */</span><br><span class="line">        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) &#123;</span><br><span class="line">            // 获取连接管理者</span><br><span class="line">            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);</span><br><span class="line">            // 获取网络状态信息</span><br><span class="line">            NetworkInfo networkInfo = manager.getActiveNetworkInfo();</span><br><span class="line">            // 判断网络信息是否为空并且已连接</span><br><span class="line">            if (null != networkInfo &amp;&amp; networkInfo.isConnected()) &#123;</span><br><span class="line">                if (ConnectivityManager.TYPE_WIFI == networkInfo.getType()) &#123;</span><br><span class="line">                    // 判断是否为Wifi</span><br><span class="line">                    Log.e(TAG, &quot;onReceive: 当前Wifi可用&quot;);</span><br><span class="line">                    Toast.makeText(context, &quot;当前Wifi可用&quot;, Toast.LENGTH_SHORT).show();</span><br><span class="line">                &#125; else if (ConnectivityManager.TYPE_MOBILE == networkInfo.getType()) &#123;</span><br><span class="line">                    // 判断是否为移动网络</span><br><span class="line">                    Log.e(TAG, &quot;onReceive: 当前移动网络可用&quot;);</span><br><span class="line">                    Toast.makeText(context, &quot;当前移动网络可用&quot;, Toast.LENGTH_SHORT).show();</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                Log.e(TAG, &quot;onReceive: info.getTypeName--&quot; + networkInfo.getTypeName());</span><br><span class="line">                Log.e(TAG, &quot;onReceive: getSubtypeName--&quot; + networkInfo.getSubtypeName());</span><br><span class="line">                Log.e(TAG, &quot;onReceive: getState--&quot; + networkInfo.getState());</span><br><span class="line">                Log.e(TAG, &quot;onReceive: getDetailedState().name--&quot; + networkInfo.getDetailedState().name());</span><br><span class="line">                Log.e(TAG, &quot;onReceive: getExtraInfo--&quot; + networkInfo.getExtraInfo());</span><br><span class="line">                Log.e(TAG, &quot;onReceive: getType--&quot; + networkInfo.getType());</span><br><span class="line"></span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                Log.e(TAG, &quot;onReceive: 当前没有网络连接，请确保你已经打开网络!&quot;);</span><br><span class="line">                Toast.makeText(context, &quot;当前没有网络连接，请确保你已经打开网络!&quot;, Toast.LENGTH_SHORT).show();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><img src="https://upload-images.jianshu.io/upload_images/3110861-9a7038b81e3f64c6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="执行效果.png"></p>
<p>####6. 网络工具类NetUtil<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * 网络工具类</span><br><span class="line"> * @author mazaiting</span><br><span class="line"> * @date 2018/3/29</span><br><span class="line"> */</span><br><span class="line"></span><br><span class="line">public class NetUtil &#123;</span><br><span class="line">    /**</span><br><span class="line">     * 判断当前网络是否是移动网络</span><br><span class="line">     *</span><br><span class="line">     * @param context 上下文</span><br><span class="line">     * @return boolean 3G</span><br><span class="line">     */</span><br><span class="line">    public static boolean is3G(Context context) &#123;</span><br><span class="line">        ConnectivityManager connectivityManager = (ConnectivityManager) context</span><br><span class="line">                .getSystemService(Context.CONNECTIVITY_SERVICE);</span><br><span class="line">        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();</span><br><span class="line">        return activeNetInfo != null</span><br><span class="line">                &amp;&amp; activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 判断当前网络是否是wifi网络</span><br><span class="line">     *</span><br><span class="line">     * @param context 上下文</span><br><span class="line">     * @return true: wifi; false: 非wifi</span><br><span class="line">     */</span><br><span class="line">    public static boolean isWifi(Context context) &#123;</span><br><span class="line">        ConnectivityManager connectivityManager = (ConnectivityManager) context</span><br><span class="line">                .getSystemService(Context.CONNECTIVITY_SERVICE);</span><br><span class="line">        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();</span><br><span class="line">        return activeNetInfo != null</span><br><span class="line">                &amp;&amp; activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 判断当前网络是否是2G网络</span><br><span class="line">     *</span><br><span class="line">     * @param context 上下文</span><br><span class="line">     * @return true: 2G; false: 不是2G</span><br><span class="line">     */</span><br><span class="line">    public static boolean is2G(Context context) &#123;</span><br><span class="line">        ConnectivityManager connectivityManager = (ConnectivityManager) context</span><br><span class="line">                .getSystemService(Context.CONNECTIVITY_SERVICE);</span><br><span class="line">        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();</span><br><span class="line">        if (null != activeNetInfo &amp;&amp; (activeNetInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_EDGE</span><br><span class="line">                || activeNetInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_GPRS || activeNetInfo</span><br><span class="line">                .getSubtype() == TelephonyManager.NETWORK_TYPE_CDMA)) &#123;</span><br><span class="line">            return true;</span><br><span class="line">        &#125;</span><br><span class="line">        return false;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * wifi是否打开</span><br><span class="line">     * @param context 上下文</span><br><span class="line">     * @return true: 打开; false: 未打开</span><br><span class="line">     */</span><br><span class="line">    public static boolean isWifiEnabled(Context context) &#123;</span><br><span class="line">        ConnectivityManager mgrConn = (ConnectivityManager) context</span><br><span class="line">                .getSystemService(Context.CONNECTIVITY_SERVICE);</span><br><span class="line">        TelephonyManager mgrTel = (TelephonyManager) context</span><br><span class="line">                .getSystemService(Context.TELEPHONY_SERVICE);</span><br><span class="line">        return ((mgrConn.getActiveNetworkInfo() != null &amp;&amp; mgrConn</span><br><span class="line">                .getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel</span><br><span class="line">                .getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 判断是否有网络连接</span><br><span class="line">     *</span><br><span class="line">     * @param context 上下文</span><br><span class="line">     * @return 网络连接</span><br><span class="line">     */</span><br><span class="line">    public static boolean isNetworkConnected(Context context) &#123;</span><br><span class="line">        if (null != context) &#123;</span><br><span class="line">            // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)</span><br><span class="line">            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context</span><br><span class="line">                    .CONNECTIVITY_SERVICE);</span><br><span class="line">            // 获取NetworkInfo对象</span><br><span class="line">            NetworkInfo networkInfo = manager.getActiveNetworkInfo();</span><br><span class="line">            //判断NetworkInfo对象是否为空</span><br><span class="line">            if (null != networkInfo) &#123;</span><br><span class="line">                return networkInfo.isAvailable();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return false;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 判断MOBILE网络是否可用</span><br><span class="line">     *</span><br><span class="line">     * @param context 上下文</span><br><span class="line">     * @return true, 可用; false，不可用</span><br><span class="line">     */</span><br><span class="line">    public static boolean isMobileConnected(Context context) &#123;</span><br><span class="line">        if (context != null) &#123;</span><br><span class="line">            //获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)</span><br><span class="line">            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context</span><br><span class="line">                    .CONNECTIVITY_SERVICE);</span><br><span class="line">            //获取NetworkInfo对象</span><br><span class="line">            NetworkInfo networkInfo = manager.getActiveNetworkInfo();</span><br><span class="line">            //判断NetworkInfo对象是否为空 并且类型是否为MOBILE</span><br><span class="line">            if (null != networkInfo &amp;&amp; networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) &#123;</span><br><span class="line">                return networkInfo.isAvailable();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return false;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 获取当前网络连接的类型信息</span><br><span class="line">     * 原生</span><br><span class="line">     *</span><br><span class="line">     * @param context 上下文</span><br><span class="line">     * @return 网络类型</span><br><span class="line">     */</span><br><span class="line">    public static int getConnectedType(Context context) &#123;</span><br><span class="line">        if (null != context) &#123;</span><br><span class="line">            //获取手机所有连接管理对象</span><br><span class="line">            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context</span><br><span class="line">                    .CONNECTIVITY_SERVICE);</span><br><span class="line">            //获取NetworkInfo对象</span><br><span class="line">            NetworkInfo networkInfo = manager.getActiveNetworkInfo();</span><br><span class="line">            if (null != networkInfo &amp;&amp; networkInfo.isAvailable()) &#123;</span><br><span class="line">                //返回NetworkInfo的类型</span><br><span class="line">                return networkInfo.getType();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return -1;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 获取当前的网络状态 ：没有网络-0：WIFI网络1：4G网络-4：3G网络-3：2G网络-2</span><br><span class="line">     * 自定义</span><br><span class="line">     *</span><br><span class="line">     * @param context 上下文</span><br><span class="line">     * @return 网络类型</span><br><span class="line">     */</span><br><span class="line">    public static int getApnType(Context context) &#123;</span><br><span class="line">        //结果返回值</span><br><span class="line">        int netType = 0;</span><br><span class="line">        //获取手机所有连接管理对象</span><br><span class="line">        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context</span><br><span class="line">                .CONNECTIVITY_SERVICE);</span><br><span class="line">        //获取NetworkInfo对象</span><br><span class="line">        NetworkInfo networkInfo = manager.getActiveNetworkInfo();</span><br><span class="line">        //NetworkInfo对象为空 则代表没有网络</span><br><span class="line">        if (networkInfo == null) &#123;</span><br><span class="line">            return netType;</span><br><span class="line">        &#125;</span><br><span class="line">        //否则 NetworkInfo对象不为空 则获取该networkInfo的类型</span><br><span class="line">        int nType = networkInfo.getType();</span><br><span class="line">        if (nType == ConnectivityManager.TYPE_WIFI) &#123;</span><br><span class="line">            //WIFI</span><br><span class="line">            netType = 1;</span><br><span class="line">        &#125; else if (nType == ConnectivityManager.TYPE_MOBILE) &#123;</span><br><span class="line">            // 获取子类型</span><br><span class="line">            int nSubType = networkInfo.getSubtype();</span><br><span class="line">            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService</span><br><span class="line">                    (Context.TELEPHONY_SERVICE);</span><br><span class="line">            if (nSubType == TelephonyManager.NETWORK_TYPE_LTE</span><br><span class="line">                    &amp;&amp; !telephonyManager.isNetworkRoaming()) &#123;</span><br><span class="line">                // 4G</span><br><span class="line">                netType = 4;</span><br><span class="line">            &#125; else if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS</span><br><span class="line">                    || nSubType == TelephonyManager.NETWORK_TYPE_HSDPA</span><br><span class="line">                    || nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0</span><br><span class="line">                    &amp;&amp; !telephonyManager.isNetworkRoaming()) &#123;</span><br><span class="line">                //3G   联通的3G为UMTS或HSDPA 电信的3G为EVDO</span><br><span class="line">                netType = 3;</span><br><span class="line">            &#125; else if (nSubType == TelephonyManager.NETWORK_TYPE_GPRS</span><br><span class="line">                    || nSubType == TelephonyManager.NETWORK_TYPE_EDGE</span><br><span class="line">                    || nSubType == TelephonyManager.NETWORK_TYPE_CDMA</span><br><span class="line">                    &amp;&amp; !telephonyManager.isNetworkRoaming()) &#123;</span><br><span class="line">                //2G 移动和联通的2G为GPRS或EGDE，电信的2G为CDMA</span><br><span class="line">                netType = 2;</span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                netType = 2;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return netType;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 获得本机ip地址</span><br><span class="line">     *</span><br><span class="line">     * @return ip地址</span><br><span class="line">     */</span><br><span class="line">    public static String getHostIp() &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            for (Enumeration&lt;NetworkInterface&gt; en = NetworkInterface</span><br><span class="line">                    .getNetworkInterfaces(); en.hasMoreElements();) &#123;</span><br><span class="line">                NetworkInterface networkInterface = en.nextElement();</span><br><span class="line">                for (Enumeration&lt;InetAddress&gt; ipAdd = networkInterface.getInetAddresses(); ipAdd</span><br><span class="line">                        .hasMoreElements(); ) &#123;</span><br><span class="line">                    InetAddress inetAddress = ipAdd.nextElement();</span><br><span class="line">                    if (!inetAddress.isLoopbackAddress()) &#123;</span><br><span class="line">                        return inetAddress.getHostAddress();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; catch (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        return null;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>####</p>
<p>####</p>
<p>####</p>
<p>####</p>
<p>####</p>
<p>####</p>
<p>####</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/Android-Special-Function/Android-横竖屏切换/" rel="next" title="Android-横竖屏切换">
                <i class="fa fa-chevron-left"></i> Android-横竖屏切换
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/Android-Special-Function/Android-跳转系统页面相关/" rel="prev" title="Android-跳转系统页面相关">
                Android-跳转系统页面相关 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
